package com.eduspace.eduplatform.wares.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * 初始化WEB工程
 *
 * @author tbc on 2016/11/21 10:19:44.
 */
@Slf4j
public class ServletInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Banner
        Banner banner = new Banner();
        banner.print();

        // .............
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(
                DruidConfiguration.class,
                MyBatisConfiguration.class,
                SpringConfiguration.class,
                SpringMVCConfiguration.class,
                Swagger2Configuration.class);
        context.setServletContext(servletContext);

        // dispatcher
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        dispatcher.addMapping("/");
        dispatcher.setLoadOnStartup(1);
        log.info("Servlet: 'dispatcher' 已注册");

        //
        ServletRegistration.Dynamic statViewServlet = servletContext.addServlet("statViewServlet", new StatViewServlet());
        statViewServlet.addMapping("/druid/*");
        //添加初始化参数：initParams
        statViewServlet.setInitParameter("loginUsername", "admin");
        statViewServlet.setInitParameter("loginPassword", "admin123");
        statViewServlet.setInitParameter("resetEnable", "false");
        log.info("Servlet: 'druidServlet' 已注册");

        //
        FilterRegistration.Dynamic druidWebStatFilter = servletContext.addFilter("DruidWebStatFilter", new WebStatFilter());
        druidWebStatFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/*");
        druidWebStatFilter.setInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        log.info("Filter: 'DruidWebStatFilter' 已注册");

    }

}